﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using TfsMerge.BO;
using TfsMerge.Interface;
using TfsMerge.Utils;
using DevExpress.XtraGrid.Views.Grid;

namespace TfsMerge.View
{
    public partial class WorkItemSelector : BaseDialog
    {
        readonly ITfs _tfs;
        public WorkItem WorkItem { get; private set; }

        public WorkItemSelector(ITfs tfs, IEnumerable<QueryItem> queries)
        {
            _tfs = tfs;

            InitializeComponent();
          
            treeList.ParentFieldName = "ParentId";
            treeList.KeyFieldName = "Id";
            treeList.DataSource = queries.ToList()
                .Select(x => new UIQueryItem(x)).ToList();

            treeList.FocusedNodeChanged += TreeListFocusedNodeChanged;
            treeList.ExpandAll();

            gridView.DoubleClick += GridViewDoubleClick;
        }

        void GridViewDoubleClick(object sender, EventArgs e)
        {
            if (!DxHelper.IsRowDoubleClick(gridControl))
                return;

            OnOkClick();
        }

        public override void OnOkClick()
        {
            WorkItem = DxHelper.GetFocusedRowAs<WorkItem>(gridControl.FocusedView as GridView);
            base.OnOkClick();
        }

        void TreeListFocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            var itm = treeList.GetDataRecordByNode(e.Node) as UIQueryItem;
            if (itm == null)
                return;

            var queryDefinition = itm.QueryItem as QueryDefinition;
            if (queryDefinition == null)
                return;

            using (var worker = new BackgroundWorker())
            {
                worker.DoWork += (sender1, e1) =>
                {
                    e1.Result = _tfs.ExecQuery(queryDefinition).ToList();
                };
                worker.RunWorkerCompleted += (sender2, e2) =>
                {
                    gridControl.BeginUpdate();
                    gridControl.DataSource = e2.Result;
                    gridControl.EndUpdate();
                };
                worker.RunWorkerAsync();
            }
        }

    }
}
